package com.qf.fronted.controller;

import com.qf.fronted.domain.Data;
import com.qf.fronted.domain.User;
import com.qf.fronted.service.UserService1;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 前端用户注册，点击"立即注册"触发
 */
@Controller
@CrossOrigin(origins = "*")  //跨域配置
public class RegisterController {

    private UserService1 userService1;

    private RegisterController(UserService1 userService1) {
        this.userService1 = userService1;
    }

    @RequestMapping("/register")
    @ResponseBody
    protected Data service(HttpServletRequest req, String username, String password, String email,
                           String gender, String phone) {
        // 前端传过来的参数样式  username=yuyy&password=1&email=7yty%40qq.com&gender=F&phone=87
        // 注册的时候密码转md5
        String md5Password = DigestUtils.md5Hex(password);
        Data data = null;
        try {
            // 返回值为当前插入的数据，数据库自动为我们生成的主键
            Integer pkValue = userService1.register(new User(username, md5Password, email, phone, gender));

            System.out.println("====" + pkValue);
            //注册成功，将用户信息设到session中
            HttpSession session = req.getSession();
            User user = new User();
            user.setId(pkValue);
            user.setName(username);
            user.setEmail(email);
            user.setPhone(phone);
            user.setSex(gender);
            session.setAttribute("user", user);

            data = new Data(1, "success");
        } catch (Exception ex) {
            ex.printStackTrace();
            data = new Data(-1, "注册失败");
        }
        return data;
    }
}
